package com.nari.ncps.screen.service.impl.electric;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.electric.ElectricProdoperHeating;
import com.nari.ncps.screen.mapper.electric.ElectricOverviewItemMapper;
import com.nari.ncps.screen.mapper.electric.ElectricProdoperHeatingMapper;



import com.nari.ncps.screen.service.electric.ElectricOverviewItemService;
import com.nari.ncps.screen.vo.electric.DailyHeatingVO;
import com.nari.ncps.screen.vo.electric.ElectricOverviewDto;
import com.nari.ncps.screen.entity.electric.ElectricOverviewItem;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 火电产业总览信息表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class ElectricOverviewItemServiceImpl extends ServiceImpl<ElectricOverviewItemMapper, ElectricOverviewItem> implements ElectricOverviewItemService {

    @Autowired
    private ElectricProdoperHeatingMapper electricProdoperHeatingMapper;

    @Resource
    private ElectricOverviewItemMapper electricOverviewItemMapper;
    /**
     * 获取火电产业总览统计数据
     * @param year 年份（必填）
     * @return 统计后的总览数据
     */
    @Override
    public ElectricOverviewDto getOverviewStatistics(Integer year) {
        // 如果year为空，使用当前年份
        if (year == null) {
            year = java.time.LocalDate.now().getYear();
        }
        
        // 创建VO对象并填充所有字段
        ElectricOverviewDto dto = new ElectricOverviewDto();
        
        // 1. 总装机容量(万千瓦)
        dto.setTotalInstalledCapacity(getTotalInstalledCapacity(year));
        
        // 2. 总负荷(万千瓦)
        dto.setTotalLoad(getTotalLoad(year));
        
        // 3. 负荷率(%)
        dto.setLoadRate(getLoadRate(year));
        
        // 4. 总利用小时(小时)
        dto.setTotalUtilizationHours(getTotalUtilizationHours(year));
        
        // 5. 全员劳动生产率(万元/人)
        dto.setLaborProductivity(getLaborProductivity(year));
        
        // 6. 日总发电量(万千瓦时)
        dto.setDailyGeneration(getDailyGeneration(year));
        
        // 7. 日上网电量(万千瓦时)
        dto.setDailyGridSupply(getDailyGridSupply(year));
        
        // 8. 日供铝用电量(万千瓦时)
        dto.setDailyAluminumSupply(getDailyAluminumSupply(year));
        
        // 9. 日供热量(吉焦)
        dto.setDailyHeatingSupply(getDailyHeatingSupply(year));
        
        // 10. 安全生产天数(天)
        dto.setSafeProductionDays(getSafeProductionDays(year));
        
        return dto;
    }

    /**
     * 总装机容量(万千瓦)
     * @param year
     * @return
     */
    public BigDecimal getTotalInstalledCapacity(Integer year) {
        LambdaQueryWrapper<ElectricOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricOverviewItem::getYear,year)
                .eq(ElectricOverviewItem::getOrgCode,100360)
                .eq(ElectricOverviewItem::getDateType,0)
                .orderByDesc(ElectricOverviewItem::getTotalInstalledCapacity)
                .last("LIMIT 1");
        ElectricOverviewItem item = electricOverviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getTotalInstalledCapacity() : null;
    }

    /**
     * 总负荷(万千瓦)
     * @param year
     * @return
     */
    public BigDecimal getTotalLoad(Integer year) {
        LambdaQueryWrapper<ElectricOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricOverviewItem::getYear,year)
                .eq(ElectricOverviewItem::getOrgCode,100360)
                .eq(ElectricOverviewItem::getDateType,0)
                .orderByDesc(ElectricOverviewItem::getTotalLoad)
                .last("LIMIT 1");
        ElectricOverviewItem item = electricOverviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getTotalLoad() : null;
    }

    /**
     * 负荷率(%)
     * @param year
     * @return
     */
    public BigDecimal getLoadRate(Integer year){
        LambdaQueryWrapper<ElectricOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricOverviewItem::getYear,year)
                .eq(ElectricOverviewItem::getOrgCode,100360)
                .eq(ElectricOverviewItem::getDateType,0)
                .orderByDesc(ElectricOverviewItem::getLoadRate)
                .last("LIMIT 1");
        ElectricOverviewItem item = electricOverviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getLoadRate() : null;
    }

    /**
     * 总利用小时(小时)
     * @param year
     * @return
     */
    public BigDecimal getTotalUtilizationHours(Integer year){
        LambdaQueryWrapper<ElectricOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricOverviewItem::getYear,year)
                .eq(ElectricOverviewItem::getOrgCode,100360)
                .eq(ElectricOverviewItem::getDateType,0)
                .orderByDesc(ElectricOverviewItem::getTotalUtilizationHours)
                .last("LIMIT 1");
        ElectricOverviewItem item = electricOverviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getTotalUtilizationHours() : null;
    }

    /**
     * 全员劳动生产率(万元/人)
     * @param year
     * @return
     */
    public BigDecimal getLaborProductivity(Integer year){
        LambdaQueryWrapper<ElectricOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricOverviewItem::getYear,year)
                .eq(ElectricOverviewItem::getOrgCode,100360)
                .eq(ElectricOverviewItem::getDateType,0)
                .orderByDesc(ElectricOverviewItem::getLaborProductivity)
                .last("LIMIT 1");
        ElectricOverviewItem item = electricOverviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getLaborProductivity() : null;
    }

    /**
     * 日总发电量(万千瓦时)
     * @param year
     * @return
     */
    public BigDecimal getDailyGeneration(Integer year){
        LambdaQueryWrapper<ElectricOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricOverviewItem::getYear,year)
                .eq(ElectricOverviewItem::getOrgCode,100360)
                .eq(ElectricOverviewItem::getDateType,0)
                .orderByDesc(ElectricOverviewItem::getDailyGeneration)
                .last("LIMIT 1");
        ElectricOverviewItem item = electricOverviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getDailyGeneration() : null;
    }

    /**
     * 日上网电量(万千瓦时)
     * @param year
     * @return
     */
    public BigDecimal getDailyGridSupply(Integer year){
        LambdaQueryWrapper<ElectricOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricOverviewItem::getYear,year)
                .eq(ElectricOverviewItem::getOrgCode,100360)
                .eq(ElectricOverviewItem::getDateType,0)
                .orderByDesc(ElectricOverviewItem::getDailyGridSupply)
                .last("LIMIT 1");
        ElectricOverviewItem item = electricOverviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getDailyGridSupply() : null;
    }

    /**
     * 日供铝用电量(万千瓦时)
     * @param year
     * @return
     */
    public BigDecimal getDailyAluminumSupply(Integer year){
        LambdaQueryWrapper<ElectricOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricOverviewItem::getYear,year)
                .eq(ElectricOverviewItem::getOrgCode,100360)
                .eq(ElectricOverviewItem::getDateType,0)
                .orderByDesc(ElectricOverviewItem::getDailyAluminumSupply)
                .last("LIMIT 1");
        ElectricOverviewItem item = electricOverviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getDailyAluminumSupply() : null;
    }

    /**
     * 日供热量(吉焦)
     * @param year
     * @return
     */
    public BigDecimal getDailyHeatingSupply(Integer year){
        LambdaQueryWrapper<ElectricOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricOverviewItem::getYear,year)
                .eq(ElectricOverviewItem::getOrgCode,100360)
                .eq(ElectricOverviewItem::getDateType,0)
                .orderByDesc(ElectricOverviewItem::getDailyHeatingSupply)
                .last("LIMIT 1");
        ElectricOverviewItem item = electricOverviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getDailyHeatingSupply() : null;
    }

    /**
     * 安全生产天数(天)
     * @param year
     * @return
     */
    public Integer getSafeProductionDays(Integer year){
        LambdaQueryWrapper<ElectricOverviewItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ElectricOverviewItem::getYear,year)
                .eq(ElectricOverviewItem::getOrgCode,100360)
                .eq(ElectricOverviewItem::getDateType,0)
                .orderByDesc(ElectricOverviewItem::getSafeProductionDays)
                .last("LIMIT 1");
        ElectricOverviewItem item = electricOverviewItemMapper.selectOne(queryWrapper);
        return item != null ? item.getSafeProductionDays() : 0;
    }
    /**
     * 查询日供热量信息
     * @param orgCode 单位编码（可选）
     * @return 日供热量信息列表，返回一个月的数据
     */
    @Override
    public List<DailyHeatingVO> getDailyHeating(String orgCode) {

//        qt_dp_electric_prodoper_heating

        LambdaQueryWrapper<ElectricProdoperHeating> lqwd = new LambdaQueryWrapper<>();
        lqwd.eq(ElectricProdoperHeating::getOrgCode, orgCode)
                .eq(ElectricProdoperHeating::getDateType,2);

        List<ElectricProdoperHeating> electricProdoperHeatings = electricProdoperHeatingMapper.selectList(lqwd);
        List<DailyHeatingVO> dailyHeatingVOS = BeanUtil.copyToList(electricProdoperHeatings, DailyHeatingVO.class);
        return dailyHeatingVOS;

//
//        // 获取当前日期
//        Date now = new Date();
//        Integer year = DateUtil.year(now);
//        Integer month = DateUtil.month(now) + 1; // hutool月份从0开始，需要+1
//
//        // 构建查询条件：查询当前年月的日数据
//        QueryWrapper<ElectricOverviewItem> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("year", year);
//        queryWrapper.eq("month", month);
//        queryWrapper.eq("date_type", 2); // 日数据
//        if (orgCode != null && !orgCode.isEmpty()) {
//            queryWrapper.eq("org_code", orgCode);
//        }
//        queryWrapper.orderByAsc("day");
//
//        List<ElectricOverviewItem> dataList = list(queryWrapper);
//
//        // 如果当前月没有数据，查询最近一个月的数据
//        if (dataList == null || dataList.isEmpty()) {
//            QueryWrapper<ElectricOverviewItem> fallbackWrapper = new QueryWrapper<>();
//            if (orgCode != null && !orgCode.isEmpty()) {
//                fallbackWrapper.eq("org_code", orgCode);
//            }
//            fallbackWrapper.eq("date_type", 2); // 日数据
//            fallbackWrapper.orderByDesc("year", "month", "day");
//
//            // 查询最近31条数据
//            fallbackWrapper.last("LIMIT 31");
//            dataList = list(fallbackWrapper);
//
//            // 反转列表，使其按日期升序
//            if (dataList != null && !dataList.isEmpty()) {
//                java.util.Collections.reverse(dataList);
//            }
//        }
//
//        // 如果还是没有数据，返回空列表
//        if (dataList == null || dataList.isEmpty()) {
//            return new ArrayList<>();
//        }
//
//        // 转换为VO对象
//        List<DailyHeatingVO> resultList = dataList.stream()
//                .map(item -> {
//                    DailyHeatingVO vo = new DailyHeatingVO();
//                    vo.setPowerPlantCode(item.getOrgCode());
//                    vo.setPowerPlantName(item.getOrgName());
//                    vo.setYear(item.getYear());
//                    vo.setMonth(item.getMonth());
//                    vo.setDay(item.getDay());
//                    vo.setDailyActualHeating(item.getDailyHeatingSupply() != null ?
//                            item.getDailyHeatingSupply() : BigDecimal.ZERO);
//                    return vo;
//                })
//                .collect(Collectors.toList());

//        return resultList;
    }

}
